package ru.compscicenter.databases.zaikina.common;

import ru.compscicenter.databases.zaikina.common.commands.EmptyCommand;
import ru.compscicenter.databases.zaikina.common.commands.SysCommand;
import ru.compscicenter.databases.zaikina.common.commands.SysCommandType;

import java.io.*;
import java.net.Socket;

public class NodeProcessor implements Runnable {
    private final Socket socket;
    private final DatabaseController controller;
    //private OutputStreamWriter out;
    //private InputStreamReader in;
    private ObjectInputStream in;// = new ObjectInputStream(socket.getInputStream());
    private ObjectOutputStream out;// = new ObjectOutputStream(socket.getOutputStream());

    public NodeProcessor(Socket socket, DatabaseController controller) {
        this.socket = socket;
        this.controller = controller;
    }

    public void run() {
        try {
           this.out = new ObjectOutputStream(socket.getOutputStream());
           this.in  = new ObjectInputStream(socket.getInputStream());

           //write(new EmptyCommand(SysCommandType.Success));
           write(controller.processCommand(readCommand()));
           //out.flush();
           //socket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public SysCommand<?, ?> readCommand() throws IOException {
        //BufferedReader br = new BufferedReader(in);
        String text;
        try {
            text = (String) in.readObject();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            return new EmptyCommand(SysCommandType.Error);
        }
        //String line;
        //while ((line = br.readLine()) != null) {
        //    text += line;
        //}
        //br.close();
        return SysCommand.parse(text);
    }

    public void write(SysCommand<?, ?> command) throws IOException {
        /*BufferedWriter writer = new BufferedWriter(out);
        writer.write(command.toJSONString());
        writer.flush();
        writer.close();*/
        out.writeObject(command.toJSONString());
        out.flush();
    }
}
